﻿using System;
using System.ComponentModel;
using System.Windows.Forms;
using log4net;
using log4net.Appender;
using log4net.Config;
using Softyum.Common.logging.appender;
using Softyum.ForexAgent.Controls;

namespace Softyum.ForexAgent.Forms
{
    public partial class MainForm : Form
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(MainForm));
        
        private LogControl logControl = new LogControl();

        private NewsControl newsControl = new NewsControl();

        public MainForm()
        {
            InitializeComponent();
        }

        #region Initialize
        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                // Log4net
                InitializeLogging();
                // UI
                InitializeUI();
                // Register hotkeys
                InitializeHotkey();
                // 
                log.Info("Application initialize success");
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                UpdateStatusBar(ex.Message);
            }
        }

        private void InitializeUI()
        {
            //
            this.toolStripStatusLabel.Text = "";
            //
            logControl.Dock = DockStyle.Fill;
            this.panel1.Controls.Add(logControl);
            //
            newsControl.Dock = DockStyle.Fill;
            this.panel1.Controls.Add(newsControl);
            logControl.Visible = false;
        }

        /// <summary>
        /// Initialize Logging
        /// </summary>
        private void InitializeLogging()
        {
            XmlConfigurator.Configure(new System.IO.FileInfo(
                Program.ConfigManager.AppDirectory + "log4net.xml"));
            foreach (IAppender item in LogManager.GetRepository().GetAppenders())
            {
                if (item.Name.Equals("TextBoxAppender"))
                {
                    TextBoxAppender appender = item as TextBoxAppender;
                    logControl.HookAppender(appender);
                }
            }
        }

        private void InitializeHotkey()
        {
            String hkString = Program.ConfigManager.Shortcut.Activate;
    
            try
            {
                HotKey.Register(Handle, Program.ConfigManager.Shortcut.Activate, OnShowHideWindow);
            }
            catch (Exception ex)
            {
                throw new Exception("Initialize hotkey failed", ex);
            }
            if (log.IsDebugEnabled)
                log.Debug("Register hotkey: " + hkString);
        }
        #endregion

        #region Overrides
        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            HotKey.ProcessHotKey(m);
        }

        protected override void DefWndProc(ref Message m)
        {
            if (m.Msg == CustomMessages.NewNews)
            {
                NEWNEWS param = CustomMessages.GetNewNewsParams(m);
                ShowMessageWindow(param.szTitle, param.szText);
            }
            else
            {
                base.DefWndProc(ref m);
            }
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            HotKey.Unregister(Handle, OnShowHideWindow);
        }
        #endregion

        private void OnShowHideWindow()
        {
            if (WindowState == FormWindowState.Minimized)
            {
                ActivateWindow();
            }
            else
            {
                this.WindowState = FormWindowState.Minimized;
            }
        }

        void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            UpdateStatusBar(e.UserState as string);
        }

        private void UpdateStatusBar(string msg)
        {
            toolStripStatusLabel.Text = msg;
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void MainForm_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized) 
            {
                this.Hide();
                this.notifyIcon.Visible = true;
            } 
        }

        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            ActivateWindow();
        }

        private void ActivateWindow()
        {
            this.Visible = true;
            this.WindowState = System.Windows.Forms.FormWindowState.Normal;
            this.notifyIcon.Visible = false;
            this.Activate();
        }
        
        #region ToolStrip Events
        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OptionsForm f = new OptionsForm();
            f.Show();
        }

        private void xPathTesterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            XPathTestForm form = new XPathTestForm();
            form.Show();
        }

        private void toolStripBtnLog_Click(object sender, EventArgs e)
        {
            SwitchView(logControl);
        }

        private void toolStripBtnNews_Click(object sender, EventArgs e)
        {
            SwitchView(newsControl);
        }

        private void newsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SwitchView(newsControl);
        }

        private void logToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SwitchView(logControl);
        }

        #endregion

        private void ShowNewsControl()
        {
            foreach (Control item in panel1.Controls)
            {
                if (item == newsControl)
                {
                    item.Visible = true;
                }
                else
                {
                    item.Visible = false;
                }
            }
        }

        private void SwitchView(Control view)
        {
            foreach (Control item in panel1.Controls)
            {
                if (item == view)
                {
                    item.Visible = true;
                }
                else
                {
                    item.Visible = false;
                }
            }
        }

        private void ShowMessageWindow(string title, string text)
        {
            if (Program.ConfigManager.PopupWindowSettings.UseBalloonTip)
            {
                if (notifyIcon.Visible == false)
                {
                    notifyIcon.Visible = true;
                    notifyIcon.BalloonTipClosed += 
                        notifyIcon_BalloonTipClosed;
                }
                notifyIcon.ShowBalloonTip(Program.ConfigManager.PopupWindowSettings.AutoCloseTimer, title, text, 
                    ToolTipIcon.Info);
            }
            else
            {
                PopupMessageForm f = new PopupMessageForm();
                f.Show(title, text);
            }
        }

        void notifyIcon_BalloonTipClosed(object sender, EventArgs e)
        {
            notifyIcon.BalloonTipClosed -= notifyIcon_BalloonTipClosed;
            notifyIcon.Visible = false;
        }

        private void explorerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SiteExplorerForm f = new SiteExplorerForm();
            f.ShowDialog();
        }
    }
}
